{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "%matplotlib inline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n",
        "[Introduction](introyt1_tutorial.html) ||\n",
        "[Tensors](tensors_deeper_tutorial.html) ||\n",
        "[Autograd](autogradyt_tutorial.html) ||\n",
        "**Building Models** ||\n",
        "[TensorBoard Support](tensorboardyt_tutorial.html) ||\n",
        "[Training Models](trainingyt.html) ||\n",
        "[Model Understanding](captumyt.html)\n",
        "\n",
        "# Building Models with PyTorch\n",
        "\n",
        "Follow along with the video below or on [youtube](https://www.youtube.com/watch?v=OSqIP-mOWOI)_.\n",
        "\n",
        ".. raw:: html\n",
        "\n",
        "   <div style=\"margin-top:10px; margin-bottom:10px;\">\n",
        "     <iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/OSqIP-mOWOI\" frameborder=\"0\" allow=\"accelerometer; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>\n",
        "   </div>\n",
        "\n",
        "## ``torch.nn.Module`` and ``torch.nn.Parameter``\n",
        "\n",
        "In this video, we’ll be discussing some of the tools PyTorch makes\n",
        "available for building deep learning networks.\n",
        "\n",
        "Except for ``Parameter``, the classes we discuss in this video are all\n",
        "subclasses of ``torch.nn.Module``. This is the PyTorch base class meant\n",
        "to encapsulate behaviors specific to PyTorch Models and their\n",
        "components.\n",
        "\n",
        "One important behavior of ``torch.nn.Module`` is registering parameters.\n",
        "If a particular ``Module`` subclass has learning weights, these weights\n",
        "are expressed as instances of ``torch.nn.Parameter``. The ``Parameter``\n",
        "class is a subclass of ``torch.Tensor``, with the special behavior that\n",
        "when they are assigned as attributes of a ``Module``, they are added to\n",
        "the list of that modules parameters. These parameters may be accessed\n",
        "through the ``parameters()`` method on the ``Module`` class.\n",
        "\n",
        "As a simple example, here’s a very simple model with two linear layers\n",
        "and an activation function. We’ll create an instance of it and ask it to\n",
        "report on its parameters:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "\n",
        "class TinyModel(torch.nn.Module):\n",
        "    \n",
        "    def __init__(self):\n",
        "        super(TinyModel, self).__init__()\n",
        "        \n",
        "        self.linear1 = torch.nn.Linear(100, 200)\n",
        "        self.activation = torch.nn.ReLU()\n",
        "        self.linear2 = torch.nn.Linear(200, 10)\n",
        "        self.softmax = torch.nn.Softmax()\n",
        "    \n",
        "    def forward(self, x):\n",
        "        x = self.linear1(x)\n",
        "        x = self.activation(x)\n",
        "        x = self.linear2(x)\n",
        "        x = self.softmax(x)\n",
        "        return x\n",
        "\n",
        "tinymodel = TinyModel()\n",
        "\n",
        "print('The model:')\n",
        "print(tinymodel)\n",
        "\n",
        "print('\\n\\nJust one layer:')\n",
        "print(tinymodel.linear2)\n",
        "\n",
        "print('\\n\\nModel params:')\n",
        "for param in tinymodel.parameters():\n",
        "    print(param)\n",
        "\n",
        "print('\\n\\nLayer params:')\n",
        "for param in tinymodel.linear2.parameters():\n",
        "    print(param)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This shows the fundamental structure of a PyTorch model: there is an\n",
        "``__init__()`` method that defines the layers and other components of a\n",
        "model, and a ``forward()`` method where the computation gets done. Note\n",
        "that we can print the model, or any of its submodules, to learn about\n",
        "its structure.\n",
        "\n",
        "## Common Layer Types\n",
        "\n",
        "### Linear Layers - 线性层\n",
        "\n",
        "The most basic type of neural network layer is a *linear* or *fully\n",
        "connected(全连接)* layer. This is a layer where every input influences every\n",
        "output of the layer to a degree specified by the layer’s weights. If a\n",
        "model has *m* inputs and *n* outputs, the weights will be an *m* x *n*\n",
        "matrix. For example:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "lin = torch.nn.Linear(3, 2) # m=3 n=2\n",
        "x = torch.rand(1, 3)\n",
        "print('Input:')\n",
        "print(x)\n",
        "\n",
        "print('\\n\\nWeight and Bias parameters:')\n",
        "for param in lin.parameters():\n",
        "    print(param)\n",
        "\n",
        "y = lin(x)\n",
        "print('\\n\\nOutput:')\n",
        "print(y)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If you do the matrix multiplication of ``x`` by the linear layer’s\n",
        "weights, and add the biases, you’ll find that you get the output vector\n",
        "``y``.\n",
        "\n",
        "One other important feature to note: When we checked the weights of our\n",
        "layer with ``lin.weight``, it reported itself as a ``Parameter`` (which\n",
        "is a subclass of ``Tensor``), and let us know that it’s tracking\n",
        "gradients with autograd. This is a default behavior for ``Parameter``\n",
        "that differs from ``Tensor``.\n",
        "\n",
        "Linear layers are used widely in deep learning models. One of the most\n",
        "common places you’ll see them is in classifier models, which will\n",
        "usually have one or more linear layers at the end, where the last layer\n",
        "will have *n* outputs, where *n* is the number of classes the classifier\n",
        "addresses.\n",
        "\n",
        "### Convolutional Layers - 卷积层\n",
        "\n",
        "*Convolutional* layers are built to handle data with a high degree of\n",
        "spatial correlation. They are very commonly used in computer vision,\n",
        "where they detect close groupings of features which the compose into\n",
        "higher-level features. They pop up in other contexts too - for example,\n",
        "in NLP applications, where a word’s immediate context (that is, the\n",
        "other words nearby in the sequence) can affect the meaning of a\n",
        "sentence.\n",
        "\n",
        "We saw convolutional layers in action in LeNet5 in an earlier video:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch.functional as F\n",
        "\n",
        "\n",
        "class LeNet(torch.nn.Module):\n",
        "\n",
        "    def __init__(self):\n",
        "        super(LeNet, self).__init__()\n",
        "        # 1 input image channel (black & white), 6 output channels, 5x5 square convolution\n",
        "        # kernel\n",
        "        self.conv1 = torch.nn.Conv2d(1, 6, 5)\n",
        "        self.conv2 = torch.nn.Conv2d(6, 16, 3)\n",
        "        # an affine operation: y = Wx + b\n",
        "        self.fc1 = torch.nn.Linear(16 * 6 * 6, 120)  # 6*6 from image dimension\n",
        "        self.fc2 = torch.nn.Linear(120, 84)\n",
        "        self.fc3 = torch.nn.Linear(84, 10)\n",
        "\n",
        "    def forward(self, x):\n",
        "        # Max pooling over a (2, 2) window\n",
        "        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n",
        "        # If the size is a square you can only specify a single number\n",
        "        x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n",
        "        x = x.view(-1, self.num_flat_features(x))\n",
        "        x = F.relu(self.fc1(x))\n",
        "        x = F.relu(self.fc2(x))\n",
        "        x = self.fc3(x)\n",
        "        return x\n",
        "\n",
        "    def num_flat_features(self, x):\n",
        "        size = x.size()[1:]  # all dimensions except the batch dimension\n",
        "        num_features = 1\n",
        "        for s in size:\n",
        "            num_features *= s\n",
        "        return num_features"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let’s break down what’s happening in the convolutional layers of this\n",
        "model. Starting with ``conv1``:\n",
        "\n",
        "-  LeNet5 is meant to take in a 1x32x32 black & white image. **The first\n",
        "   argument to a convolutional layer’s constructor is the number of\n",
        "   input channels.** Here, it is 1. If we were building this model to\n",
        "   look at 3-color channels, it would be 3.\n",
        "-  A convolutional layer is like a window that scans over the image,\n",
        "   looking for a pattern it recognizes. These patterns are called\n",
        "   *features,* and one of the parameters of a convolutional layer is the\n",
        "   number of features we would like it to learn. **This is the second\n",
        "   argument to the constructor is the number of output features.** Here,\n",
        "   we’re asking our layer to learn 6 features.\n",
        "-  Just above, I likened the convolutional layer to a window - but how\n",
        "   big is the window? **The third argument is the window or kernel\n",
        "   size.** Here, the “5” means we’ve chosen a 5x5 kernel. (If you want a\n",
        "   kernel with height different from width, you can specify a tuple for\n",
        "   this argument - e.g., ``(3, 5)`` to get a 3x5 convolution kernel.)\n",
        "\n",
        "The output of a convolutional layer is an *activation map* - a spatial\n",
        "representation of the presence of features in the input tensor.\n",
        "``conv1`` will give us an output tensor of 6x28x28; 6 is the number of\n",
        "features, and 28 is the height and width of our map. (The 28 comes from\n",
        "the fact that when scanning a 5-pixel window over a 32-pixel row, there\n",
        "are only 28 valid positions.)\n",
        "\n",
        "We then pass the output of the convolution through a ReLU activation\n",
        "function (more on activation functions later), then through a max\n",
        "pooling layer. The max pooling layer takes features near each other in\n",
        "the activation map and groups them together. It does this by reducing\n",
        "the tensor, merging every 2x2 group of cells in the output into a single\n",
        "cell, and assigning that cell the maximum value of the 4 cells that went\n",
        "into it. This gives us a lower-resolution version of the activation map,\n",
        "with dimensions 6x14x14.\n",
        "\n",
        "Our next convolutional layer, ``conv2``, expects 6 input channels\n",
        "(corresponding to the 6 features sought by the first layer), has 16\n",
        "output channels, and a 3x3 kernel. It puts out a 16x12x12 activation\n",
        "map, which is again reduced by a max pooling layer to 16x6x6. Prior to\n",
        "passing this output to the linear layers, it is reshaped to a 16 \\* 6 \\*\n",
        "6 = 576-element vector for consumption by the next layer.\n",
        "\n",
        "There are convolutional layers for addressing 1D, 2D, and 3D tensors.\n",
        "There are also many more optional arguments for a conv layer\n",
        "constructor, including stride length(e.g., only scanning every second or\n",
        "every third position) in the input, padding (so you can scan out to the\n",
        "edges of the input), and more. See the\n",
        "[documentation](https://pytorch.org/docs/stable/nn.html#convolution-layers)_\n",
        "for more information.\n",
        "\n",
        "### Recurrent Layers - 循环层\n",
        "\n",
        "*Recurrent neural networks* (or *RNNs)* are used for sequential data -\n",
        "anything from time-series measurements from a scientific instrument to\n",
        "natural language sentences to DNA nucleotides. An RNN does this by\n",
        "maintaining a *hidden state* that acts as a sort of memory for what it\n",
        "has seen in the sequence so far.\n",
        "\n",
        "The internal structure of an RNN layer - or its variants, the LSTM (long\n",
        "short-term memory) and GRU (gated recurrent unit) - is moderately\n",
        "complex and beyond the scope of this video, but we’ll show you what one\n",
        "looks like in action with an LSTM-based part-of-speech tagger (a type of\n",
        "classifier that tells you if a word is a noun, verb, etc.):\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "class LSTMTagger(torch.nn.Module):\n",
        "\n",
        "    def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size):\n",
        "        super(LSTMTagger, self).__init__()\n",
        "        self.hidden_dim = hidden_dim\n",
        "\n",
        "        self.word_embeddings = torch.nn.Embedding(vocab_size, embedding_dim)\n",
        "\n",
        "        # The LSTM takes word embeddings as inputs, and outputs hidden states\n",
        "        # with dimensionality hidden_dim.\n",
        "        self.lstm = torch.nn.LSTM(embedding_dim, hidden_dim)\n",
        "\n",
        "        # The linear layer that maps from hidden state space to tag space\n",
        "        self.hidden2tag = torch.nn.Linear(hidden_dim, tagset_size)\n",
        "\n",
        "    def forward(self, sentence):\n",
        "        embeds = self.word_embeddings(sentence)\n",
        "        lstm_out, _ = self.lstm(embeds.view(len(sentence), 1, -1))\n",
        "        tag_space = self.hidden2tag(lstm_out.view(len(sentence), -1))\n",
        "        tag_scores = F.log_softmax(tag_space, dim=1)\n",
        "        return tag_scores"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The constructor has four arguments:\n",
        "\n",
        "-  ``vocab_size`` is the number of words in the input vocabulary. Each\n",
        "   word is a one-hot vector (or unit vector) in a\n",
        "   ``vocab_size``-dimensional space.\n",
        "-  ``tagset_size`` is the number of tags in the output set.\n",
        "-  ``embedding_dim`` is the size of the *embedding* space for the\n",
        "   vocabulary. An embedding maps a vocabulary onto a low-dimensional\n",
        "   space, where words with similar meanings are close together in the\n",
        "   space.\n",
        "-  ``hidden_dim`` is the size of the LSTM’s memory.\n",
        "\n",
        "The input will be a sentence with the words represented as indices of\n",
        "one-hot vectors. The embedding layer will then map these down to an\n",
        "``embedding_dim``-dimensional space. The LSTM takes this sequence of\n",
        "embeddings and iterates over it, fielding an output vector of length\n",
        "``hidden_dim``. The final linear layer acts as a classifier; applying\n",
        "``log_softmax()`` to the output of the final layer converts the output\n",
        "into a normalized set of estimated probabilities that a given word maps\n",
        "to a given tag.\n",
        "\n",
        "If you’d like to see this network in action, check out the [Sequence\n",
        "Models and LSTM\n",
        "Networks](https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html)_\n",
        "tutorial on pytorch.org.\n",
        "\n",
        "### Transformers - 转换器\n",
        "\n",
        "*Transformers* are multi-purpose networks that have taken over the state\n",
        "of the art in NLP with models like BERT. A discussion of transformer\n",
        "architecture is beyond the scope of this video, but PyTorch has a\n",
        "``Transformer`` class that allows you to define the overall parameters\n",
        "of a transformer model - the number of attention heads, the number of\n",
        "encoder & decoder layers, dropout and activation functions, etc. (You\n",
        "can even build the BERT model from this single class, with the right\n",
        "parameters!) The ``torch.nn.Transformer`` class also has classes to\n",
        "encapsulate the individual components (``TransformerEncoder``,\n",
        "``TransformerDecoder``) and subcomponents (``TransformerEncoderLayer``,\n",
        "``TransformerDecoderLayer``). For details, check out the\n",
        "[documentation](https://pytorch.org/docs/stable/nn.html#transformer-layers)_\n",
        "on transformer classes, and the relevant\n",
        "[tutorial](https://pytorch.org/tutorials/beginner/transformer_tutorial.html)_\n",
        "on pytorch.org.\n",
        "\n",
        "## Other Layers and Functions\n",
        "\n",
        "### Data Manipulation Layers - 数据操作层\n",
        "\n",
        "There are other layer types that perform important functions in models,\n",
        "but don’t participate in the learning process themselves.\n",
        "\n",
        "**Max pooling** (and its twin, min pooling) reduce a tensor by combining\n",
        "cells, and assigning the maximum value of the input cells to the output\n",
        "cell (we saw this). For example:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "my_tensor = torch.rand(1, 6, 6)\n",
        "print(my_tensor)\n",
        "\n",
        "maxpool_layer = torch.nn.MaxPool2d(3)\n",
        "print(maxpool_layer(my_tensor))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "If you look closely at the values above, you’ll see that each of the\n",
        "values in the maxpooled output is the maximum value of each quadrant of\n",
        "the 6x6 input.\n",
        "\n",
        "**Normalization layers** re-center and normalize the output of one layer\n",
        "before feeding it to another. Centering the and scaling the intermediate\n",
        "tensors has a number of beneficial effects, such as letting you use\n",
        "higher learning rates without exploding/vanishing gradients.\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "my_tensor = torch.rand(1, 4, 4) * 20 + 5\n",
        "print(my_tensor)\n",
        "\n",
        "print(my_tensor.mean())\n",
        "\n",
        "norm_layer = torch.nn.BatchNorm1d(4)\n",
        "normed_tensor = norm_layer(my_tensor)\n",
        "print(normed_tensor)\n",
        "\n",
        "print(normed_tensor.mean())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Running the cell above, we’ve added a large scaling factor and offset to\n",
        "an input tensor; you should see the input tensor’s ``mean()`` somewhere\n",
        "in the neighborhood of 15. After running it through the normalization\n",
        "layer, you can see that the values are smaller, and grouped around zero\n",
        "- in fact, the mean should be very small (> 1e-8).\n",
        "\n",
        "This is beneficial because many activation functions (discussed below)\n",
        "have their strongest gradients near 0, but sometimes suffer from\n",
        "vanishing or exploding gradients for inputs that drive them far away\n",
        "from zero. Keeping the data centered around the area of steepest\n",
        "gradient will tend to mean faster, better learning and higher feasible\n",
        "learning rates.\n",
        "\n",
        "**Dropout layers** are a tool for encouraging *sparse representations*\n",
        "in your model - that is, pushing it to do inference with less data.\n",
        "\n",
        "Dropout layers work by randomly setting parts of the input tensor\n",
        "*during training* - dropout layers are always turned off for inference.\n",
        "This forces the model to learn against this masked or reduced dataset.\n",
        "For example:\n",
        "\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "my_tensor = torch.rand(1, 4, 4)\n",
        "\n",
        "dropout = torch.nn.Dropout(p=0.4)\n",
        "print(dropout(my_tensor))\n",
        "print(dropout(my_tensor))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Above, you can see the effect of dropout on a sample tensor. You can use\n",
        "the optional ``p`` argument to set the probability of an individual\n",
        "weight dropping out; if you don’t it defaults to 0.5.\n",
        "\n",
        "### Activation Functions - 激活函数\n",
        "\n",
        "Activation functions make deep learning possible. A neural network is\n",
        "really a program - with many parameters - that *simulates a mathematical\n",
        "function*. If all we did was multiple tensors by layer weights\n",
        "repeatedly, we could only simulate *linear functions;* further, there\n",
        "would be no point to having many layers, as the whole network would\n",
        "reduce could be reduced to a single matrix multiplication. Inserting\n",
        "*non-linear* activation functions between layers is what allows a deep\n",
        "learning model to simulate any function, rather than just linear ones.\n",
        "\n",
        "``torch.nn.Module`` has objects encapsulating all of the major\n",
        "activation functions including ReLU and its many variants, Tanh,\n",
        "Hardtanh, sigmoid, and more. It also includes other functions, such as\n",
        "Softmax, that are most useful at the output stage of a model.\n",
        "\n",
        "### Loss Functions - 损失函数\n",
        "\n",
        "Loss functions tell us how far a model’s prediction is from the correct\n",
        "answer. PyTorch contains a variety of loss functions, including common\n",
        "MSE (mean squared error = L2 norm), Cross Entropy Loss and Negative\n",
        "Likelihood Loss (useful for classifiers), and others.\n",
        "\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)]"
    },
    "vscode": {
      "interpreter": {
        "hash": "cf18841ace8313d0bc088ca146c17a6c0040e82121d5cb75c0ea07172309253d"
      }
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
